class MyPage extends BaseList {
    constructor(action, orderby, flag, $pagesize, $pagination, cokiePageSize, cokiePageIndex, cokieListResult, listUrl, delUrl) {
        super(action, orderby, flag, $pagesize, $pagination, cokiePageSize, cokiePageIndex, cokieListResult, listUrl, delUrl);
        this.selectedItemList = {};  // 选定的数据列表OnMultiChoice
        this.draggedItemList = [];
        this.filterCatalogueFlag = 1;
        this.dragging = 0;
    }
    OnPageLoad() {
        let _pageindex = $.cookie(this.cokiePageIndex) === undefined ? 1 : $.cookie(this.cokiePageIndex);
        if (this.flag === 0) {
            _pageindex = 1;
        } else {
            this.RestoreFilters();  // 恢复过滤条件
        }
        this.$pagination.attr("_msh_page", _pageindex);

        _InstanceTree.InitTreeObject();
    }
    SetCriterion(item) {
        // 设置目录条件
        if (parseInt(this.filterCatalogueFlag) === 1) {
            item['CatalogueId'] = parseInt($.trim($('#NodeId').val()) === '' ? 0 : $.trim($('#NodeId').val()));
        }
        // 设置检索条件       
        item['UserNameFilterValue'] = $.trim($('#UserNameFilterValue').val()) === '' ? null : $.trim($('#UserNameFilterValue').val());
        return item;
    }
    GetFilter(pageIndex) {
        let item = super.GetFilter(pageIndex);
        // 设置条件
        item = this.SetCriterion(item);
        return JSON.stringify(item);
    }
    FetchByFilter() {
        this.filterCatalogueFlag = 0;
        this.FetchForPage(1);
    }
    FetchAll() {
        $("#UserNameFilterValue").val("");

        this.filterCatalogueFlag = 1;
        this.$pagination.attr("_msh_page", 1);
        this.FetchForPage(1);
    }
    EmptyTableContent() {
        $("#tabData01 tbody").empty();
        this.$pagination.attr("_msh_page", 1);
    }
    SetTableContent(result) {
        $("#tabData01 tbody").empty();

        let content_01 = '';
        this.numCheckbox = result.length;  // 设置表格中checkbox的数量为表格的行数
        for (let i = 0; i < result.length; i++) {
            content_01 = '<tr _mash_user_id="' + result[i].userId + '">';
            content_01 += '<td style="padding-left:5px; vertical-align:middle;"><label class="btn" for="R-' + result[i].userId + '"><input id="R-' + result[i].userId + '" name="_check_row" type="checkbox" onclick="_Instance.DoCheckRow($(this),\'_check_row\', $(\'#CheckAll\'));" value="' + result[i].userId + '"/><i></i><span></span></label></td>';
            content_01 += '<td class="column__action"><span title="删除" class="trash" onclick="_Instance.DoDelete($(this));"><i class="fa-all fa-trash-o fa-1"></i></span></td>';
            content_01 += '<td>' + result[i].userName + '</td>';
            content_01 += '<td></td>';
            content_01 += '<td>' + formatNullData(result[i].department) + '</td>';
            content_01 += '</tr>';

            $("#tabData01 tbody").append(content_01);
            content_01 = '';
        }
        setOneTableRowColor("tabData01");
        /*
        let _this = this;
        // 为拖动做准备
        $("#tabData01 tbody tr").mousedown(function (event) {
            if (_this.draggable === 1)
                return false;
            // 如果鼠标按下的位置 正好是选择框，则不做拖动处理
            if ($(event.target).closest("td").index() === 0)
                return false;
            if (parseInt($(this).attr("_msh_flag")) === 1)
                return false;  // 如果是系统用户，则不做任何操作
            if ($(this).hasClass("row__selected") === true) {
                _this.draggable = 1;
                event.preventDefault();
                _InstanceTree.CreateDragLayer(event);
                _this.GetDragData();
                $(window).mousemove(function (event) {
                    event.preventDefault();
                    _InstanceTree.FollowMe(event);
                }).mouseup(function (event) {
                    _this.draggable = 0;
                    _this.draggedItemList = [];
                    $(window).unbind('mousemove');
                    $(window).unbind('mouseup');

                    if ($("#moveLayerId").length) {
                        $("#moveLayerId").remove();
                    }
                });
            }
        });*/

        this.ResetSelectRowStatus();  // 恢复选定结果
    }
    DoEditCatalogue() {
        // 设置当前页
        $.cookie(this.cokiePageIndex, parseInt(this.$pagination.attr("_msh_page")));
        // 保存过滤条件
        this.SaveFilters();
        location.assign(parent.basePath + '/master/user_group/catalogue/edit.html');
    }
    DoInsert() {
        if (($("#NodeId").val() === "") || (parseInt($("#NodeId").val()) === 0)) {
            ShowErrorMessagePanel('系统提示：必须选择一个目录。');
            return false;
        }
        let _choice = new CommonChoice();
        _choice.DoChoiceUser(1, '选择人员', null, (data) => {
            if (data) {
                let _list = [];
                for (var i = 0; i < data.length; i++) {
                    var item = {};
                    item['userId'] = parseInt(data[i].EmployeeId);
                    item['catalogueId'] = parseInt($.trim($("#NodeId").val()));
                    item['createdBy'] = parseInt($.trim($("#UserId").val()));
                    item['updatedBy'] = parseInt($.trim($("#UserId").val()));

                    _list.push(item);
                }

                let _params = super.GetFilter(this.$pagination.attr("_msh_page"));
                // 设置条件
                _params = this.SetCriterion(_params);
                _params['ItemList'] = _list;
                // 保存，根据所选产品款号，增加明细表记录
                super.DoAjax(_params, "/master/user_group/member/insert.html", function (data, _this) {
                    if (data.Success === true) {
                        _this.BuildDataTable(data);
                    } else {
                        _this.EmptyTableContent();
                    }
                    ShowSuccessMessagePanel("增加成功。");
                });
            }
        });
    }
    DoDelete($self) {
        let _params = super.GetFilter(this.$pagination.attr("_msh_page"));
        // 设置条件
        _params = this.SetCriterion(_params);
        _params['UserId'] = parseInt($self.parent().parent().attr("_mash_user_id"));
        _params['CatalogueId'] = parseInt($("#NodeId").val());
        _params['DeletedUserName'] = $self.parent().parent().find("td").eq(2).text();
        _params['DeletedBy'] = $("#UserId").val();
        super.DoDelete(_params, function (_this, data) {
            if (data.Success === true) {
                _this.BuildDataTable(data);
            } else {
                _this.EmptyTableContent();
            }
            ShowSuccessMessagePanel("删除成功。");
        });
    }
    // 设置行选择后的状态
    SetRowStatus($self) {
        super.AdjustRowStatus($self, ($row, index) => {
            let key = $self.val();
            let item = {};
            // 设置 编辑、删除按钮失效
            $row.children('td').eq(1).children('span').eq(0).attr("onclick", "");
            // 为翻页选择做准备
            item["supplierId"] = key;
            this.selectedItemList[key] = item;
        }, ($row, index) => {
            let key = $self.val();
            // 设置 编辑、删除按钮有效
            let _event_delete_onclick = '_Instance.DoDelete($(this))';
            $row.children('td').eq(1).children('span').eq(0).attr("onclick", _event_delete_onclick);
            delete this.selectedItemList[key];
        });
    }
    // 每次翻页都恢复选定结果
    ResetSelectRowStatus() {
        let _this = this;
        $("#tabData01 tbody").find("tr").each(function (index) {
            let key = $(this).attr("_mash_user_id");
            if (_this.selectedItemList[key] !== undefined) {
                $(this).children("td").eq(0).children("label").eq(0).children("input[type='checkbox'][name='_check_row']").eq(0).prop('checked', true);
                $(this).addClass("row__selected");
            }
        });
        // 设置选择全部的状态
        let n = $("input[type='checkbox'][name='_check_row']:checked").length;
        if (n < $("#tabData01 tbody").find("tr").length || n === 0) {
            $("#CheckAll").prop("checked", false);
        } else {
            $("#CheckAll").prop("checked", true);
        }
    }
    GetDragData() {
        let _this = this;
        this.draggedItemList = [];
        if ($("input[type='checkbox'][name='_check_row']:checked").length > 0) {
            $("input[type='checkbox'][name='_check_row']:checked").each(function () {
                let item = {};
                item['userId'] = $(this).val();
                item['updatedBy'] = $("#UserId").val();
                _this.draggedItemList.push(item);
            });
        } else {
            let item = {};
            item['userId'] = parseInt($("#tabData01 tbody tr.rowMoved").attr("_mash_user_id"));
            item['updatedBy'] = parseInt($("#UserId").val());
            _this.draggedItemList.push(item);
        }
    }
    SaveFilters() {
        let _filters = new Array();
        _filters.push($("#UserNameFilterValue").val());
        $.cookie("user_group_membert_fiters", _filters.join(","));
    }
    RestoreFilters() {
        if ($.cookie("user_group_membert_fiters") !== undefined && this.flag !== 0) {
            let _filters = $.cookie("user_group_membert_fiters").split(',');
            $("#UserNameFilterValue").val(_filters[0]);
        } else {
            $("#UserNameFilterValue").val("");
        }
    }
    Expand() {
        let _w = $(window).width();
        $("#btnPanel_01").show();
        $("#treeArea").show();
        $("#panelSplitter").css({left: 250});
        $("#panelSplitter").children().removeClass("fa-angle-double-right").addClass("fa-angle-double-left");
        $("#panelSplitter").attr("title", "折叠目录");

        $("#btnPanel_02").css({left: 275});
        $("#grid__wrapper").css({left: 275, width: _w - 8 - 275});
    }
    Collapse() {
        let _w = $(window).width();
        $("#btnPanel_01").hide();
        $("#treeArea").hide();
        $("#panelSplitter").css({left: 0});
        $("#panelSplitter").children().removeClass("fa-angle-double-left").addClass("fa-angle-double-right");
        $("#panelSplitter").attr("title", "展开目录");

        $("#btnPanel_02").css({left: 24});
        $("#grid__wrapper").css({width: _w - 24 - 8, left: 24});
    }
}

class MyPageTree extends BaseTree {
    constructor(instance, getTreeUrl, dragUrl, stateKey) {
        super(instance, getTreeUrl, dragUrl, stateKey);
        this.draggable = 0;
    }
}

var _Instance = null;
var _InstanceTree = null;

//-----------------------------------------------------------------------------
// 页面初始化
//-----------------------------------------------------------------------------
function onPageReady() {
    let flag = jQuery.url.param("flag") === undefined ? 0 : jQuery.url.param("flag");
    $("#page-size").val($.cookie("user_group_membert_pagesize") === undefined ? 15 : $.cookie("user_group_membert_pagesize"));
    // 删除已经保存的检索后的数据列表标识数组
    $.cookie("user_group_membert_result", null);

    _Instance = new MyPage(0, null, flag,
            $("#page-size"),
            $("abbr.page_indicator_block,#wrapper__navbar"),
            "user_group_membert_pagesize",
            "user_group_membert_pageindex",
            "user_group_membert_result",
            "/master/user_group/member/fetchForPage.html",
            "/master/user_group/member/delete.html");
    _InstanceTree = new MyPageTree(_Instance, "/master/user_group/catalogue/tree.html",
            "/master/user_group/member/changeCatalogue.html",
            "user_group_member_selected_node");

    //设置分页控制 （操作区域）
    $("#wrapper__navbar").swPagination({
        link_string: '/?page={page_number}',
        max_page: null,
        paged: function (page) {
            $("abbr.page_indicator_block,#wrapper__navbar").attr("_msh_page", page);
            _Instance.FetchForPage(page);
        }
    });

    $("#panelSplitter").click(function () {
        if ($(this).children("i").hasClass("fa-angle-double-left")) {
            _Instance.Collapse();
        } else {
            _Instance.Expand();
        }
    });

    _Instance.OnPageLoad();
}

// 画面大小或者位置移动
function onPageResize() {
    let h = $(window).height();

    $("#treeArea").css({height: h - 110});
}